﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Subgurim.Controles;
using System.Configuration;
using System.IO;
using KishOnlineDomain.Controller;

public partial class KishCar_Pages_EditCarStore : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (UserController.GetCurrentUser() == null)
        {
            Response.Redirect("Home.aspx");
        }
        Session.Remove("IsSucceed");
        if (!Page.IsPostBack)
        {

            if (GetFileUploader().IsPosting)
            {
                this.managePost();
            }
            if (GetFileUploader().IsDeleting)
            {
            }

        }
        int CarStoreID = -1;
        if (Request.QueryString["ID"] != null)
        {
            int.TryParse(Request.QueryString["ID"], out CarStoreID);
        }        
        CarControllers CarControl = new CarControllers();
        if (CarStoreID > 0)
        {

            KishOnlineCommone.CarDTOs.CarStoreDTO CarStore = CarControl.CarSotre.Get(CarStoreID);
            if (!Page.IsPostBack && CarStore.File != null )
            {
                GetFileUploader().Visible = false;
            }
            int i = 0;
            if (CarStore.File != null)
            {
                if (!string.IsNullOrEmpty(CarStore.File.Path))
                {
                    //Image CurrentImage = new Image();//Page.FindControl("CarImage" + (i + 1).ToString()) as Image;
                    Control TempContorl = Page.LoadControl("~/Common/UC/ImageControl.ascx");
                    Image CurrentImage = TempContorl.FindControl("Image") as Image;
                    CurrentImage.ID = "CarImage_" + (i + 1).ToString();
                    CurrentImage.ImageUrl = CarStore.File.Path;
                    ImageButton DelImage = TempContorl.FindControl("DelImageButton") as ImageButton;
                    DelImage.ID = (CarStore.File.ID).ToString();
                    DelImage.Click += new ImageClickEventHandler(DelImage_Click);
                    CarImagesUpdatePanel.ContentTemplateContainer.Controls.Add(TempContorl);

                    CarImagesUpdatePanel.Visible = true;
                }
                GetFileUploader().MaxFiles = 0;
            }
            else
            {
                GetFileUploader().MaxFiles = 1;
            }
        }
    }

    void DelImage_Click(object sender, EventArgs e)
    {
        ImageButton DelButton = sender as ImageButton;
        long ImageID = Convert.ToInt64(DelButton.ID);
        RemoveCarImage(ImageID);
        CarImagesUpdatePanel.ContentTemplateContainer.Controls.Remove(DelButton.Parent);
        GetFileUploader().MaxFiles++;
        GetFileUploader().Visible = true;
    }

    private void managePost()
    {
        lblMsg.Text = "";
        HttpPostedFileAJAX pf;
        pf = GetFileUploader().PostedFile;
        try
        {
            string tempFolder = ConfigurationManager.AppSettings["tempFolder"];
            //make a virtual directory
            string path = tempFolder.Replace("~", "../..");
            //if (!Directory.Exists(path))
            //{
            //    MakeDir(path);
            //}
            //send a full address not a virtual address
            string extension = System.IO.Path.GetExtension(pf.FileName).Split('.').Last();
            string fileName = pf.FileName.Split('.').First();

            using (var db = KishOnlineDomain.Common.Utility.GetDataContext())
            {
                var allEx = db.AllowedExtensions.Select(s => s.Name).ToList();
                if (allEx.Contains(extension.ToLower()))
                {
                    if (GetFileUploader().FileContent.Length < 200 * 1024)
                    {
                        string unique = Guid.NewGuid().ToString().Substring(0, 7);
                        string newFileName = fileName + "_" + unique + '.' + extension;
                        GetFileUploader().SaveAs(path, newFileName);
                        if (Session["picName"] != null)
                        {
                            var filenames = Session["picName"] as List<string>;
                            filenames.Add(newFileName);
                            Session["picName"] = filenames;
                        }
                        else
                        {
                            Session["picName"] = new List<string>() { newFileName };
                        }
                        Session["IsSucceed"] = true;
                    }
                }
                else
                {
                    lblMsg.Text = "لطفا تصویری با فرمت های شناخته شده بار گذاری کنید";
                }
            }

        }
        catch (Exception e)
        {
            lblMsg.Text = "Error;" + e.Message;
            Session["IsSucceed"] = false;
            return;
        }

    }


    private string MakeDir(string path)
    {
        return Directory.CreateDirectory(path).FullName;
    }
    private KishOnlineCommone.ResultDTO RemoveCarImage(long ImageID)
    {
        return KishOnlineDomain.Common.ImageRemover.GetImageRemover(KishOnlineDomain.Common.ImageType.ImageCar).DeleteImage(ImageID);
    }

    private FileUploaderAJAX GetFileUploader()
    {
        return CarImagesUpdatePanel.ContentTemplateContainer.FindControl("FileUploaderAJAX1") as FileUploaderAJAX;
    }  
}